package cn.blnp.net.flowable.boot.ext.consumer;

import cn.blnp.net.flowable.boot.bean.dto.CusJobMessage;
import cn.blnp.net.flowable.boot.ext.manager.RocketMqMessageBasedJobManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.flowable.engine.ManagementService;
import org.flowable.job.api.Job;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * <h3>自定义工作流任务消费者</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/23 17:38
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = RocketMqMessageBasedJobManager.JOB_TOPIC,
        consumerGroup = RocketMqMessageBasedJobManager.JOB_CONSUMER_GROUP,
        consumeMode = ConsumeMode.ORDERLY
)
public class CusJobConsumer implements RocketMQListener<CusJobMessage> {

    @Resource
    private ManagementService managementService;

    @Override
    public void onMessage(CusJobMessage jobMessage) {
        log.info("Consumer job message {}", jobMessage);
        Job job = managementService.createJobQuery()
                .jobId(jobMessage.getJobId())
                .singleResult();
        if (Optional.ofNullable(job).isPresent()) {
            managementService.executeJob(jobMessage.getJobId());
        }
    }
}
